package com.quanta.edaily.utils;

import com.auth0.jwt.JWT;
import com.quanta.edaily.mapper.UserMapper;
import com.quanta.edaily.pojo.User;
import jakarta.annotation.PostConstruct;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

@Component
public class TokenUtils {

    @Resource
    private UserMapper userMapper;

    private static UserMapper staticUserMapper;

    @PostConstruct
    public void setUserMapper() {
        staticUserMapper = userMapper;
    }

    public static User getCurrentUser() {
        try {
            HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
            String token = request.getHeader("Authorization");
            if(token==null || token.isEmpty()) return null;
            String id = JWT.decode(token).getAudience().get(0);
            return staticUserMapper.getUserById(Integer.valueOf(id));
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }
}
